package com.metagurukul.metagranth.actionservlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.metagurukul.metagranth.exception.MetaSqlException;
import com.metagurukul.metagranth.service.AnswerService;
import com.metagurukul.metagranth.vo.Answer;

/**
 * Servlet implementation class PostAnswerServlet
 * This servlet performs the functioanlity of Post answer function
 * @author team MetaGranth
 *
 */
public class PostAnswerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public PostAnswerServlet() {
		super();
		
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPerform(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPerform(request, response);
	}

	/**
	 * this function will get the questionId of a particular question.Get the answerDescription ,checks for the session 
	 * of the loggedin user, gets his userId and set the questionId ,answerDescription and userId by value objects
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doPerform(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		if(session.getAttribute("userId")!=null){
		try {
		int questionId = Integer.parseInt(request.getParameter("questionId"));
		String answerDescription = request.getParameter("answerdescription");
		int userId = Integer.parseInt(session.getAttribute("userId").toString());
		System.out.println("questionID"+questionId+"userID"+userId+"answer"+answerDescription);
		Answer answer = new Answer();
		answer.setQid(questionId);
		answer.setUid(userId);
		answer.setAnswer(answerDescription);

	
			int status = AnswerService.saveAnswer(answer);
			if (status > 0) {
				response.sendRedirect("question-discription.do?questionId="	+ questionId);
			}
		} catch (MetaSqlException exception) {
			request.setAttribute("errormsg", exception.getMessage());
			request.getRequestDispatcher("errorPage.jsp").forward(request,response);
		}
		} else {
			response.sendRedirect("index.jsp");
		}
	}

}
